const router = require('koa-router')()
const fs = require('fs')

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

router.post('/list', async (ctx, next) => {
  console.log(ctx.request.body);
  
  let args = [
    {field: 'page', type: 'number'},
    {field: 'count', type: 'number'},
  ];

  let body = ctx.request.body;

  for(let i = 0; i < args.length; ++i){
    let item = args[i];
    if( !Object.keys(body).includes(item.field) ){
        ctx.body = {
          errcode: -1,
          errmsg: '参数个数错误',
        };
        return;
    } else {
        if( typeof body[item.field] != item.type) {
          ctx.body = {
            errcode: -2,
            errmsg: '参数类型错误',
          };
          return;          
        }
    }
  }
  
  let data = fs.readFileSync('C:\\Users\\dell\\Desktop\\learningAjax\\learningAjax\\data\\list.json');
  data = JSON.parse(data);

  let list = data.splice( body.page * body.count, body.count);

  ctx.body = {
    errcode: 0,
    errmsg: 'ok',
    list  
  };
})

module.exports = router
